<template>
  <a-modal :open="isOpen" :title="props.editData.penId ? '编辑' : '新增'" @ok="handleAddEdit" @cancel="onCancel">
    <a-form ref="formRef" :model="addObj">
      <a-form-item
        label="圈舍名称"
        name="penName"
        :rules="[
          { required: true, message: '请输入圈舍名称' },
          { max: 10, message: '最多输入10个字符' },
        ]"
      >
        <a-input v-model:value="addObj.penName"></a-input>
      </a-form-item>

      <a-form-item label="牧场" name="ranchId" :rules="[{ required: true, message: '请选择牧场' }]">
        <a-select
          v-model:value="addObj.ranchId"
          :options="ranchOptions"
          optionLabelProp="label"
          :disabled="!!addObj.penId"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<!-- :disabled="!!addObj.penId" -->
<script setup>
import { ref, defineEmits, defineProps, watchEffect } from 'vue';
import PenManage from '@/api/pen';
import { message } from 'ant-design-vue';
const emits = defineEmits(['cancel', 'success']);

// 接收父组件
const formRef = ref(null);
const props = defineProps({
  isOpen: {
    type: Boolean,
    required: true,
  },
  editData: {
    type: Object,
  },
});
const addObj = ref(props.editData ? { ...props.editData } : {});

// onCancel 事件
const onCancel = () => {
  emits('cancel');
  formRef.value.resetFields();
};

const handleAddEdit = async () => {
  // 先对数据进行校验
  await formRef.value.validateFields();
  // 判断是否有id
  const isEdit = !!addObj.value.penId;

  if (isEdit) {
    await PenManage.editPen(addObj.value);
    // debugger;
    console.log(addObj.value);

    message.success('编辑成功');
  } else {
    await PenManage.addPen(addObj.value);
    message.success('新增成功');
  }
  emits('success');
  formRef.value.resetFields();
};

// 定义选项
const ranchOptions = ref([]);
const getItemRanchList = async () => {
  const res = await PenManage.getRanchList();
  console.log(res);
  ranchOptions.value = res.data.data.map((item) => ({
    label: item.ranchName,
    value: item.ranchId,
  }));
};
getItemRanchList();

// 监听 editData 的变化
watchEffect(() => {
  // debugger;
  addObj.value = { ...props.editData };
});
</script>

<style></style>
